/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EditWindow.java
 *
 * Created on 19.09.2011, 02:30:03
 */
package de.hijacksoft.isledesktopsync;

import de.hijacksoft.isle.classes.Item;
import de.hijacksoft.isledesktopsync.adapter.DBAdapter;
import java.io.File;
import java.util.ArrayList;
import javax.swing.JFileChooser;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Philipp
 */
public class EditWindow extends javax.swing.JFrame {
    
    private static EditWindow instance = null;
    private DBAdapter dbadapter = new DBAdapter();
    
    private File dbFile = null;
    
    LocalizationManager localization;
    
    public static EditWindow getInstance(){
        if(instance == null) instance = new EditWindow();
        return instance;
    }
    
    /** Creates new form EditWindow */
    private EditWindow() {
        initComponents();
        saveButton.setVisible(false);
        String lastdb = SettingsManager.getInstance().getString(Globals.SETTING_LASTDB);
        if(lastdb != null){
            loadDatabase(dbadapter.readDBFromFile(new File(lastdb)));
        }
        initLocalization();        
    }
    
    private void initLocalization() {
        localization = LocalizationManager.getInstance();
        openButton.setText(getString("opendb"));
    }
    
    public String getString(String key){
        try {
            return localization.getString(key);
        } catch (Exception ex) {
            System.out.println(ex.toString());
        }
        return null;
    }
    
    private void loadDatabase(ArrayList<Item> items){
        DefaultTableModel model = new DefaultTableModel(null, new String[]{"ID", "Name", "Amount", "Unit", "Price", "Lastbought", "Period", "Barcode", "Category ID"});

        for(Item item : items){
            model.addRow(new Object[]{item.id, item.name, item.amount, item.unit, item.price, item.lastbought, item.avgperiod, item.barcode, item.category.id});
        }
        
        table.setModel(model);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        saveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        openButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Item Database Editor");

        saveButton.setText("Save");
        saveButton.setEnabled(false);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Name", "Amount", "Unit", "Price", "Lastbought", "Period", "Barcode", "Category ID"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.Double.class, java.lang.String.class, java.lang.Double.class, java.lang.Long.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane1.setViewportView(table);

        openButton.setText("Open...");
        openButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 687, Short.MAX_VALUE)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(openButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 123, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 407, Short.MAX_VALUE)
                .add(saveButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 123, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(saveButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(openButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 40, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle(getString("opendb"));
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(false);
        if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            loadDatabase(new DBAdapter().readDBFromFile(chooser.getSelectedFile().getAbsolutePath()));
            dbFile = chooser.getSelectedFile();
            this.setTitle(chooser.getSelectedFile().getAbsolutePath());
            SettingsManager.getInstance().saveString(Globals.SETTING_LASTDB, chooser.getSelectedFile().getAbsolutePath());
            saveButton.setEnabled(true);
        }
    }//GEN-LAST:event_openButtonActionPerformed
    
    private ArrayList<Item> getArrayListFromTable(){
        ArrayList<Item> list = new ArrayList<Item>();
        
        for(int row = 0; row < table.getRowCount(); row++){
            
            String str = "";
            for(int column = 0; column < table.getColumnCount(); column++){
                str += table.getValueAt(row, column).toString();
                if(!table.getColumnName(column).equals("Amount")) str += ", ";
            }
            list.add(Item.getItemFromString(str));
            
        }
        return list;
    }
    
    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        dbadapter.storeDB(getArrayListFromTable(), dbFile.getAbsolutePath());
    }//GEN-LAST:event_saveButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JButton openButton;
    public javax.swing.JButton saveButton;
    public javax.swing.JTable table;
    // End of variables declaration//GEN-END:variables
}
